//
//  LGPlaceViewController.m
//  LoverGo
//
//  Created by YeXiao on 14-1-14.
//  Copyright (c) 2014年 yexiao. All rights reserved.
//

#import "LGPlaceViewController.h"
#import "LGRequestManager.h"
#import "LGPlaceInfo.h"
#import "LGDataCenter.h"
#import "LGPlaceItemView.h"
#import "LGPlaceDetailViewController.h"

@interface LGPlaceViewController ()

@end

@implementation LGPlaceViewController

-(id)initWithTitle:(NSString *)title image:(UIImage *)img type:(MainViewType)mvtype
{
    self = [super init];
    if (self) {
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:img tag:mvtype];
    }
    return self;
}


-(void)loadView
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPlaceByMap:) name:getPlaceByMapSPath object:nil];
    _placeView = [[LGPlaceView alloc] initWithFrame:CGRectMake(0, STATUSBAR, SCREEN_WIDTH, SCREEN_HEIGHT - STATUSBAR - TOOLBAR)];
    _placeView.delegate = self;
    _placeView.qtmquitView.delegate = self;
    _placeView.qtmquitView.dataSource = self;
    [self setView:_placeView];
    _placeArray = [[NSMutableArray alloc] init];
    
    [_placeView reloadAllData];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}
-(void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:getPlaceByMapSPath name:nil object:self];
}


-(void)getPlaceByMap:(NSNotification *)nof
{
    
    
    id obj = [nof object];
    if (!obj) {
        return;
    }
    if ([obj isKindOfClass:[LGPlaceByMapInfo class]]) {
        [_placeArray addObject:obj];
        [_placeView reloadAllData];//刷新数据
    }else if([obj isKindOfClass:[NSString class]])
    {
        [[LGRequestManager getSingleton] starLoading:@"加载失败" Type:ShowLoading Enabled:NO];
    }
    
}

//刷新delegate
#pragma mark -
#pragma mark data reloading methods that must be overide by the subclass

-(void)beginToReloadData:(LGPlaceView*)pView RefreshType:(EGORefreshPos)aRefreshPos{
    
    if (aRefreshPos == EGORefreshHeader)
	{
        // pull down to refresh data//下拉刷新
        if (_placeArray && [_placeArray count] > 0)
        {
            //如果有，那么，清楚数据然后重新加载
            [_placeArray removeAllObjects];
            
        }
        [[LGRequestManager getSingleton] sendRequest:NULL mapper:[LGPlaceByMapInfo getObjectMapping] serverPath:getPlaceByMapSPath jsonPath:@"" canTouch:NO];
    }else if(aRefreshPos == EGORefreshFooter)
	{
        // pull up to load more data
        //翻页
        if (_placeArray && [_placeArray count] > 0)
        {
            LGPlaceByMapInfo *lastInfo = [_placeArray objectAtIndex:([_placeArray count] - 1)];
            if (lastInfo.nowPage +1 >= lastInfo.totalPage)
            {
                //最后一页了
                return;
            }
            NSDictionary *para = [[NSDictionary alloc] initWithObjectsAndKeys:
                                  [NSString stringWithFormat:@"%d",lastInfo.nowPage +1],@"page",
                                  nil];

            [[LGRequestManager getSingleton] sendRequest:para mapper:[LGPlaceByMapInfo getObjectMapping] serverPath:getPlaceByMapSPath jsonPath:@"" canTouch:NO];
        }else
        {
            //取第一页
            [[LGRequestManager getSingleton] sendRequest:NULL mapper:[LGPlaceByMapInfo getObjectMapping] serverPath:getPlaceByMapSPath jsonPath:@"" canTouch:NO];
        }
    }
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	if (_placeView.refreshHeaderView)
	{
        [_placeView.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
	
	if (_placeView.refreshFooterView)
	{
        [_placeView.refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	if (_placeView.refreshHeaderView)
	{
        [_placeView.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
	
	if (_placeView.refreshFooterView)
	{
        [_placeView.refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}
- (CGFloat)quiltView:(TMQuiltView *)quiltView heightForCellAtIndexPath:(NSIndexPath *)indexPath
{
    return 102;//item的高度
}
- (CGFloat)quiltViewMargin:(TMQuiltView *)quilView marginType:(TMQuiltViewMarginType)marginType
{
    return 2.0f;//item边距
}
- (NSInteger)quiltViewNumberOfCells:(TMQuiltView *)TMQuiltView {
    if (_placeArray && [_placeArray count] > 0) {
        LGPlaceByMapInfo *lastInfo = [_placeArray objectAtIndex:([_placeArray count] - 1)];
//        NSLog(@"num::::%d\n",(([_placeArray count] - 1) * lastInfo.rowsPerPage + [lastInfo.listData count]));
        return (([_placeArray count] - 1) * lastInfo.rowsPerPage + [lastInfo.listData count]);
    }
    return 0;
}

- (TMQuiltViewCell *)quiltView:(TMQuiltView *)quiltView cellAtIndexPath:(NSIndexPath *)indexPath {
    LGPlaceItemView *cell = (LGPlaceItemView *)[quiltView dequeueReusableCellWithReuseIdentifier:@"ItemCell"];
    if (!cell) {
        cell = [[LGPlaceItemView alloc] initWithReuseIdentifier:@"LGPlaceItemView"];
    }
    
//    [cell setFrame:CGRectMake(0, 0, 320, 160)];
    
    LGPlaceInfo* info = [self getPlaceInfoWithIndex:indexPath.row];
    if (info) {
        [cell reloadData:info];
    }
    return cell;
}
-(LGPlaceInfo*)getPlaceInfoWithIndex:(int)index
{
    if (_placeArray && [_placeArray count] > 0) {
        LGPlaceByMapInfo *lastInfo = [_placeArray objectAtIndex:([_placeArray count] - 1)];
        int arrayIndex = 0;
        int readIndex = 0;
        if (lastInfo.rowsPerPage > 0) {
            arrayIndex = index /lastInfo.rowsPerPage;
            readIndex =index %lastInfo.rowsPerPage;
        }
        LGPlaceByMapInfo *readInfo = [_placeArray objectAtIndex:arrayIndex];
        CUJSONMapper *mapper = [LGPlaceInfo getObjectMapping];
        if ([readInfo.listData count] > readIndex) {
            LGPlaceInfo* info = [mapper objectFromJSONDictionary:[readInfo.listData objectAtIndex:readIndex ]];
            return info;
        }
    }
    return nil;
}

- (void)quiltView:(TMQuiltView *)quiltView didSelectCellAtIndexPath:(NSIndexPath *)indexPath
{
    LGPlaceInfo* info = [self getPlaceInfoWithIndex:indexPath.row];
    if (info) {
        LGPlaceDetailViewController *vc = [[LGPlaceDetailViewController alloc] initWithUuid:info.uuid];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
